package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.dto.Result;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.*;
import com.gistone.commis.query.QueryOvertime;
import com.gistone.commis.query.QueryPerson;
import com.gistone.commis.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.xsom.XSWildcard;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.io.File;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiOvertimeController")
@RequestMapping("api/overtime")

public class OvertimeController {

    private static final Logger logger = LoggerFactory.getLogger(OvertimeController.class);


    @Value("${app.uploadPath}")
    private String path;
    @Autowired
    private OvertimeMapper overtimeMapper;

    @Autowired
    private OvertimeNotifyMapper overtimeNotifyMapper;

    @Autowired
    private CommunityMapper communityMapper;


    @Autowired
    private UserMapper userMapper;


    @Autowired
    private GetBySqlMapper getBySqlMapper;


    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageNotifyDatatables")
    public DataTablePageUtil<Map> pageNotifyDatatables(HttpServletRequest request, @RequestParam  Integer flag ) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        Calendar now = Calendar.getInstance();
        int nowYear =now.get(Calendar.YEAR);
        int nowMonth =now.get(Calendar.MONTH) + 1;
        String sql = "select tb_overtime_notify.*,tb_community.community_name  from tb_overtime_notify,tb_community where tb_overtime_notify.community_id =tb_community.community_id  and year  =" +nowYear+" and month =" +nowMonth+" and flag =" +flag;

        DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Map> list =		this.getBySqlMapper.findRecords(sql);
        PageInfo<Map> pageInfo =new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }

    @RequestMapping("/alterFlag")
    public Result alterFlag(@RequestParam Integer flag,@RequestParam Integer communityId, HttpServletResponse response) throws Exception {
        Date d= new Date();
        Calendar now = Calendar.getInstance();
        int nowYear =now.get(Calendar.YEAR);
        int nowMonth =now.get(Calendar.MONTH) + 1;


        if(overtimeNotifyMapper.selectByCommunityAndYearAndMonth(communityId,nowYear,nowMonth).size()>0){

            OvertimeNotify overtimeNotify =overtimeNotifyMapper.selectByCommunityAndYearAndMonth(communityId,nowYear,nowMonth).get(0);

            overtimeNotify.setFlag(flag);
            overtimeNotifyMapper.updateByPrimaryKeySelective(overtimeNotify);
            if(flag==1) {//确定数据正确
                return new Result(Status.SUCCESS, "确定成功", "");
            }else  if(flag==3){//返回修改
                return  new Result(Status.SUCCESS,"成功返回修改",null);
            }else{
                return  new Result(Status.SUCCESS,"成功",null);
            }

        }else{
            return  new Result(Status.ERROR,"所选社区还没有上传对应数据",null);
        }







    }

    @RequestMapping("/isExist")
    public Result isExist(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {
        List<File> fileList = new ArrayList<>();


        String downloadPath =path+"/加班/"+year+"/"+month;
        File file =new File(downloadPath);
        if(file.isDirectory()){
            File[] files =file.listFiles();
            for (File file1 : files) {
                fileList.add(file1);
            }
        }
        if(fileList.size()>0){
            return new Result("exist");
        }else{
            return  new Result(Status.ERROR,"没有数据文件",null);
        }


    }


    @RequestMapping("/isJbfExist")
    public Result isJbfExist(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {


        List<Community> communityList = communityMapper.selectCommunitysWithout1();

        for (Community community : communityList) {

            if (overtimeMapper.selectByCommunityAndYearAndMonth(community.getCommunityId(),year,month).size()==0){
                return  new Result(Status.ERROR,community.getCommunityName()+"-"+year+"-"+month+"对应年月的数据上报不完整，不能导出对应加班费表\n",null);
            }

        }
        return new Result("exist");








    }


    @RequestMapping("/btDownload")
    public void btDownload(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {
        List<File> fileList = new ArrayList<>();

        String tmpFileName = "加班"+"-"+year+"-"+month+".zip";

        String downloadPath =path+"/加班/"+year+"/"+month;
        File file =new File(downloadPath);
        if(file.isDirectory()){
            File[] files =file.listFiles();
            for (File file1 : files) {
                fileList.add(file1);
            }
        }


        ZipUtil.downLoadFiles(fileList,tmpFileName,response);









    }

    @Autowired
    private PersonMapper personMapper;
    @RequestMapping("/jbfDownload")
    public void jbfDownload(@RequestParam Integer year,@RequestParam Integer month, HttpServletResponse response) throws Exception {
        String fileName = "加班费"+year+"-"+month+".xls";
        String sheetName = "加班费";//sheet名
        String []title = new String[]{"序号","姓名","社区","加班费"};//标题


        QueryPerson qp =new QueryPerson();
        qp.setIsDelete(0);
//        qp.setCommunityId(5);
        qp.setNoCommunityId(1);


        List<Person> list = personMapper.selectSelective(qp);//内容list


        String [][]values = new String[list.size()][];
        for(int i=0;i<list.size();i++){
            values[i] = new String[title.length];
            //将对象内容转换成string
            Person person = list.get(i);
            values[i][0] = person.getNumber()+"";
            values[i][1] = person.getPersonName()+"";
            values[i][2] = person.getCommunity().getCommunityName()+"";

            Overtime overtime =overtimeMapper.selectByPersonAndYearAndMonth(person.getPersonId(),year,month);

            double jbf = overtime.getOtLength()*15+overtime.getOtType()*20;
            if(jbf>300){
                jbf =300;
            }

            values[i][3] = jbf+"";


        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);

        //将文件存到指定位置
        try {
            ResponseHeaderUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }










    }



    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<Overtime> pageDatatables(HttpServletRequest request, QueryOvertime overtime) {



        DataTablePageUtil<Overtime> dataTable = new DataTablePageUtil<>(request);

        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Overtime> list = overtimeMapper.selectSelective(overtime);

        PageInfo<Overtime> pageInfo = new PageInfo<>(list);
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
//        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }




    /**
     * 批量加班信息， id以,号分割
     *
     * @param overtimeIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String overtimeIdStr, HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = overtimeIdStr.split(",");
        EditorResult<Overtime> overtimeEditorResult = new EditorResult<>();
        List<Overtime> data =new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            int overtimeId = Integer.valueOf(arr[i]);
            Overtime overtime = new Overtime();
            overtime.setOvertimeId(overtimeId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getOvertime(request, "data[" + overtimeId + "][", overtime,fieldErrorList);
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                overtimeEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return overtimeEditorResult;
            }
            if (overtimeMapper.updateByPrimaryKeySelective(overtime) > 0) {
                Overtime h = overtimeMapper.selectByPrimaryKey(overtimeId);
                data.add(h);








            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        overtimeEditorResult.setData(data);
        return overtimeEditorResult;


    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Result create(HttpServletRequest request,
                         @RequestParam("ids[]") int [] ids,
//                         @RequestParam("otTime[]") String [] otTime,
                         @RequestParam("otLength[]") Double [] otLength,
                         @RequestParam("otType[]") Double [] otType,
                   /*      @RequestParam("otReason[]") String [] otReason,
                         @RequestParam("otType[]") String [] otType,*/
                         Integer repeat,


                         HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        if(null==user){
            return  new Result(Status.NOUSER,"用户不存在!",null);
        }
        user =userMapper.selectByPrimaryKey(user.getUserId());
        Date d= new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

        List< Overtime> overtimeList=overtimeMapper.selectByCommunityAndYearAndMonth(user.getCommunityId(),year,month);

        if(overtimeList.size()>0&&null==repeat){
            return  new Result(Status.REPEAT,"已经存在当月加班数据!",null);
        }
        System.out.println(user.getCommunityId());
        for (int i=0;i<ids.length;i++) {
            int id =ids[i];
            Overtime overtime =new Overtime();
            if(null!=repeat&&repeat==1){
                overtime =overtimeMapper.selectByPersonAndYearAndMonth(id,year,month);
                if(null==overtime){
                    return  new Result(Status.ERROR,"发生错误!",null);
                }
                overtime.setUserId(user.getUserId());
                overtime.setPersonName(user.getRealName());
                overtime.setRegisterTime(d);
                overtime.setOtLength(otLength[i]);
                overtime.setOtType(otType[i]);
                if(overtimeMapper.updateByPrimaryKey(overtime)>0){
                    logger.info("更新成功");

                }else {
                    return  new Result(Status.ERROR,"更新失败",null);
                }



            }else{
                overtime.setPersonId(id);
                overtime.setCommunityId(user.getCommunityId());
                overtime.setDepartId(user.getDepartId());
                overtime.setUserId(user.getUserId());
                overtime.setPersonName(personMapper.selectByPrimaryKey(id).getPersonName());

                overtime.setRegisterTime(d);


                overtime.setOtLength(otLength[i]);
                overtime.setOtType(otType[i]);



                overtime.setOtYear(year);

                overtime.setOtMonth(month);

                if(overtimeMapper.insert(overtime)>0){
                    logger.info("插入成功");

                }else {
                    return  new Result(Status.ERROR,"插入失败",null);
                }

            }






        }

        List<OvertimeNotify> overtimeNotifyList =overtimeNotifyMapper.selectByCommunityAndYearAndMonth(user.getCommunityId(),year,month);
        OvertimeNotify overtimeNotify;
        if(overtimeNotifyList.size()>0){
            overtimeNotify =overtimeNotifyList.get(0);
            overtimeNotify.setFlag(2);
            overtimeNotifyMapper.updateByPrimaryKey(overtimeNotify);


        }else{

            overtimeNotify =new OvertimeNotify();
            overtimeNotify.setFlag(2);//代表已上传
            overtimeNotify.setMonth(month);
            overtimeNotify.setYear(year);
            overtimeNotify.setCommunityId(user.getCommunityId());
            overtimeNotifyMapper.insertSelective(overtimeNotify);
        }


        logger.info("批量插入成功");
        return  new Result(Status.SUCCESS,"批量插入成功",null);



    }
    private void getOvertime(HttpServletRequest request, String prefix, Overtime overtime,  List<FieldError> fieldErrorList ) {



  /*      try {
            overtime.setOtTime(DateUtil.StrToDate1(request.getParameter(prefix + "otTime]")));
        } catch (Exception e) {
            logger.error("时间格式不正确，必须为YYYY-MM-DD");
            FieldError fieldError =new FieldError("otTime","时间格式不正确，必须为YYYY-MM-DD时间格式不正确，必须为YYYY-MM-DD");
            fieldErrorList.add(fieldError);
        }*/



        try {
            overtime.setOtLength(Double.valueOf(request.getParameter(prefix + "otLength]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("otLength","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }
     /*   overtime.setOtReason(request.getParameter(prefix + "otReason]"));
        overtime.setOtType(request.getParameter(prefix + "otType]"));
*/


    }


}
